package com.road.yishi.execaction;

import java.util.LinkedList;
import java.util.Queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * *
 * 
 * <pre>
 * CmdTaskQueue基本功能实现
 * </pre>
 * 
 * @author jackson.zhang
 *
 */
public class AbstractCmdTaskQueue implements CmdTaskQueue {

	private final static Logger LOG = LoggerFactory.getLogger(AbstractCmdTaskQueue.class);

	private Queue<CmdTask> queue;
	private CmdExecutor executor;

	public AbstractCmdTaskQueue(CmdExecutor executor) {
		this.executor = executor;
		this.queue = new LinkedList<CmdTask>();
	}

	@Override
	public CmdTaskQueue geCmdTaskQueue() {
		return this;
	}

	@Override
	public void enqueue(CmdTask cmdTask) {
		boolean canExec = false;
		synchronized (queue) {
			if (queue != null) {
				queue.add(cmdTask);
				if (queue.size() == 1) {
					canExec = true;
				} else if (queue.size() > 3000) {
					LOG.warn(cmdTask.toString() + " queue size : " + queue.size());
				}
			}
		}

		if (canExec) {
			executor.execute(cmdTask);
		}
	}

	@Override
	public void dequeue(CmdTask cmdTask) {
		CmdTask nextCmdTask = null;
		synchronized (queue) {
			if (queue.size() == 0) {
				LOG.error("queue.size() is 0.");
			}

			CmdTask temp = queue.remove();
			if (temp != cmdTask) {
				LOG.error("action queue error. temp " + temp.toString() + ", action : " + cmdTask.toString());
			}

			if (queue.size() != 0) {
				nextCmdTask = queue.peek();
			}
		}

		if (nextCmdTask != null) {
			executor.execute(nextCmdTask);
		}
	}

	@Override
	public Queue<CmdTask> getQueue() {
		return queue;
	}

	@Override
	public void clear() {
		synchronized (queue) {
			if (queue != null) {
				queue.clear();
			}
		}
	}

}
